//
//  MePurseViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/25.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "MePurseViewController.h"
#import "MainViewController.h"
#import "WithdrawWXViewController.h"

//Cell
#import "MePurseHeadCell.h"
#import "MePurseClassifyTableViewCell.h"
#import "MePurseSectionHeadCell.h"

//Request
#import "HTTPPromise+Me.h"

//Model
#import "MeHTModel.h"

//Tools
#import "MJRefresh.h"
#import "MJRefreshCustomHeader.h"
#import "AppUtil.h"

@interface MePurseViewController ()<UITableViewDelegate,UITableViewDataSource,MePurseSectionHeadDelegate>
{
    dispatch_queue_t queue;
    
    //取出数据
    NSMutableArray<MePurseListModel *> *PurseListData;
    
    int downNumber;
}
@property (strong, nonatomic) IBOutlet UITableView *MePurseTableView;
@property (strong, nonatomic) MePurseModel *purseModel;

@end

@implementation MePurseViewController
#pragma mark -init
#define MePurseSectionHeadIdentifyCell  @"MePurseSectionHeadCell"
#define MePurseHeadIdentifyCell  @"MePurseHeadCell"
#define MePurseClassifyIdentifyCell  @"MePurseClassifyCell"

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //设置header
    UINib *contentHeaderNib = [UINib nibWithNibName:NSStringFromClass([MePurseHeadCell class])
                                       bundle:[NSBundle mainBundle]];
    [self.MePurseTableView registerNib:contentHeaderNib forCellReuseIdentifier:MePurseHeadIdentifyCell];
    
    UINib *contentNib = [UINib nibWithNibName:NSStringFromClass([MePurseClassifyTableViewCell class])
                                       bundle:[NSBundle mainBundle]];
    [self.MePurseTableView registerNib:contentNib forCellReuseIdentifier:MePurseClassifyIdentifyCell];
    
    
    //设置header
    UINib *headernib = [UINib nibWithNibName:NSStringFromClass([MePurseSectionHeadCell class]) bundle:[NSBundle mainBundle]];
    [self.MePurseTableView registerNib:headernib forCellReuseIdentifier:MePurseSectionHeadIdentifyCell];
    
    [self initTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"我的钱包"];
    
    MainViewController *mainCtrol = (MainViewController *)self.tabBarController;
    [mainCtrol hiddenTabBar];
    
    downNumber = 1;
    [self initRequest];
}

- (void)initRequest
{
    queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_group_t group = dispatch_group_create();
    
    //设置信号总量为1，保证只有一个进程执行
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    
    dispatch_async(queue, ^{
        //等待信号量
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        NSData *purseData;
        
        if ([NSJSONSerialization isValidJSONObject: @{}])
        {
            NSError *error;
            purseData = [NSJSONSerialization dataWithJSONObject:@{} options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json =[[NSString alloc] initWithData:purseData encoding:NSUTF8StringEncoding];
            NSLog(@"json data:%@",json);
        }
        
        __weak __typeof(self)weakSelf = self;
        [HTTPPromise requestMineWalletParams:purseData Success:^(id responseObj) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            NSLog(@"%@",responseObj);
            int successRet =[responseObj[@"ret"] intValue];
            //(数据转模型）
            if (successRet == 0) {
                strongSelf.purseModel = [[MePurseModel alloc] init];
                strongSelf.purseModel.total = [responseObj[@"total"] floatValue];
                strongSelf.purseModel.surplus = [responseObj[@"surplus"] floatValue];
            }else{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [AppUtil showTipMessage:responseObj[@"desc"]];
                });
            }
            
            dispatch_semaphore_signal(semaphore);  //发送一个信号
        } failure:^(NSError *error) {
            NSLog(@"%@",error.userInfo);
            dispatch_semaphore_signal(semaphore); //发送一个信号
        }];
    });
    
    
    dispatch_async(queue, ^(){
        //等待信号量
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        NSDictionary *purseListParam = @{@"pageNo":[NSNumber numberWithInt:downNumber],@"pageSize":@"20"};
        NSData *jsonData;
        
        if ([NSJSONSerialization isValidJSONObject:purseListParam])
        {
            NSError *error;
            jsonData = [NSJSONSerialization dataWithJSONObject:purseListParam options:NSJSONWritingPrettyPrinted error:&error];
            NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json data:%@",json);
        }
        
//        dispatch_group_enter(group);
        __weak __typeof(self)weakSelf = self;
        [HTTPPromise requestWithdrawHistoryParams:jsonData Success:^(id responseObj) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            NSLog(@"%@",responseObj);

            int successRet =[responseObj[@"ret"] intValue];
            //(数据转模型）
            if (successRet == 0) {
                NSArray *tempArr = responseObj[@"list"];
                if (downNumber == 1 ) {
                    
                    strongSelf->PurseListData = [[NSMutableArray alloc] init];
                    
                    [strongSelf assembleData:tempArr];
                }else{
                    [strongSelf assembleData:tempArr];
                }
            }else{
                [AppUtil showTipMessage:responseObj[@"desc"]];
            }
            
            dispatch_semaphore_signal(semaphore);  //发送一个信号
        } failure:^(NSError *error) {
            NSLog(@"%@",error.userInfo);
            dispatch_semaphore_signal(semaphore);  //发送一个信号
        }];
    });
    
}

- (void)initTableView{
    _MePurseTableView.tableFooterView = [[UIView alloc] init];
    
    __weak __typeof(self)weakSelf = self;
    _MePurseTableView.mj_header = [MJRefreshCustomHeader headerWithRefreshingBlock:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf->downNumber = 1;
        [strongSelf initRequest];
        
        NSArray *footerSub = _MePurseTableView.mj_footer.subviews;
        for (UILabel *temp in footerSub) {
            if (temp.isHidden == YES) {
                temp.hidden = NO;
                break;
            }
        }
        [strongSelf.MePurseTableView.mj_header endRefreshing];
    }];
    // 隐藏时间
    ((MJRefreshCustomHeader *)_MePurseTableView.mj_header).lastUpdatedTimeLabel.hidden = YES;
    
    _MePurseTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        strongSelf->downNumber ++;
        strongSelf.MePurseTableView.mj_footer.hidden = NO;
        
        NSArray *footerSub = strongSelf->_MePurseTableView.mj_footer.subviews;
        for (UILabel *temp in footerSub) {
            if (temp.isHidden == YES) {
                temp.hidden = NO;
                break;
            }
        }
        
        if (downNumber == 1) {
            [strongSelf initRequest];
        }else
        {
            strongSelf.MePurseTableView.mj_footer.hidden = YES;
        }
        [strongSelf.MePurseTableView.mj_footer endRefreshing];
    }];
}

#pragma mark -MePurseDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        if(_purseModel !=nil){
            return 1;
        }
        return 0;
    }else if (section == 1)
    {
        if (PurseListData != nil && PurseListData.count > 0) {
            return PurseListData.count + 1;
        }
    }
    return 0;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
            MePurseSectionHeadCell *mePurseSectionCell = [tableView dequeueReusableCellWithIdentifier:MePurseSectionHeadIdentifyCell];
            [mePurseSectionCell configureCell:_purseModel];
            mePurseSectionCell.selectionStyle = UITableViewCellSelectionStyleNone;
            mePurseSectionCell.headDelegate = self;
            
            return mePurseSectionCell;
    }else{
        if (indexPath.row == 0) {
            MePurseHeadCell *mePurseHeadCell = [tableView dequeueReusableCellWithIdentifier:MePurseHeadIdentifyCell];
            [mePurseHeadCell configureCell:_purseModel];
            mePurseHeadCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return mePurseHeadCell;
        }else{
            MePurseClassifyTableViewCell *mePurseClassifyCell = [tableView dequeueReusableCellWithIdentifier:MePurseClassifyIdentifyCell];
            
            [mePurseClassifyCell configureCell:PurseListData[indexPath.row - 1]];
            mePurseClassifyCell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return mePurseClassifyCell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 90;
    }else{
        if (indexPath.row == 0) {
            return 90;
        }
        return 70;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 90;
    }else{
        if (indexPath.row == 0) {
            return 90;
        }
        return 70;
    }
    return 44;
}

#pragma mark -MePurseSectionHeadDelegate
- (void)skipController
{
    WithdrawWXViewController *withdrawWXVC = [[WithdrawWXViewController alloc] init:_purseModel.surplus];
    [self.navigationController pushViewController:withdrawWXVC animated:YES];
}

#pragma mark -private
- (void)assembleData:(NSArray *)data
{
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MePurseListModel *listModel = [[MePurseListModel alloc] init];
        [listModel setValuesForKeysWithDictionary:obj];
        [PurseListData addObject:listModel];
    }];
    
    [_MePurseTableView reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
